<template>
    <!-- 头部标题 -->
    <h2 class="settings-title">个人设置</h2>

    <!-- 主体内容 -->
    <el-row :gutter="40">
      <!-- 左侧头像区域 -->
      <el-col :md="8" :sm="24">
        <div class="avatar-section">
          <Upload :src="form.avatarUrl"
                  :previewImage="previewImage"
                  :handleAvatarChange="handleAvatarChange"
                  :before-avatar-upload="beforeAvatarUpload"/>
          <p class="avatar-tip">支持JPG/PNG格式，大小不超过2MB</p>
        </div>
      </el-col>

      <!-- 右侧表单区域 -->
      <div style="width: 800px;">
        <el-col :md="16" :sm="24">
          <el-form
              ref="formRef"
              :model="form"
              :rules="rules"
              label-width="120px"
              label-position="left"
          >
            <!-- 基本信息 -->
            <div class="form-section">
              <h3 class="section-title">基本信息</h3>
              <el-form-item label="用户名"  prop="username">
                <el-input
                    v-model="form.username"
                    placeholder="请输入用户名"
                    clearable
                />
              </el-form-item>

              <el-form-item label="电子邮箱" prop="email">
                <el-input
                    v-model="form.email"
                    placeholder="请输入邮箱"
                    type="email"
                />
              </el-form-item>

              <el-form-item label="手机号码" prop="phone">
                <el-input
                    v-model="form.phone"
                    placeholder="请输入手机号"
                    maxlength="11"
                />
              </el-form-item>
            </div>

            <!-- 安全设置 -->
            <div class="form-section">
              <h3 class="section-title">安全设置</h3>
              <el-form-item label="旧密码" prop="oldPassword">
                <el-input
                    v-model="form.oldPassword"
                    type="password"
                    show-password
                />
              </el-form-item>

              <el-form-item label="新密码" prop="newPassword">
                <el-input
                    v-model="form.newPassword"
                    type="password"
                    show-password
                />
              </el-form-item>

              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                    v-model="form.confirmPassword"
                    type="password"
                    show-password
                />
              </el-form-item>
            </div>

            <!-- 提交按钮 -->
            <el-form-item>
              <el-button
                  type="primary"
                  :loading="submitting"
                  @click="submitForm"
              >
                保存设置
              </el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </div>
    </el-row>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {getUserInfo} from "@/api/acconut.js";
import {userInform} from "@/stores/userInform.js";
import Upload from "@/components/Upload.vue";
import {PostFileUserImg} from "@/api/file.js";
import {updateRePassword} from "@/api/user.js";
import router from "@/router"

// 表单数据
const form = reactive({
  avatarUrl: '',
  username: '',
  email: '',
  phone: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const userInformPink = userInform()

const getFormData = async () => {
  const res = await getUserInfo(userInformPink.username)
  if(res.code === 200){
    form.avatarUrl = res.data.avatarUrl
    form.username = res.data.username
    form.email = res.data.email
    form.phone = res.data.phone
  }
}

// 自定义验证方法
const validatePassword = (rule, value, callback) => {
  if (value && value.length < 6) {
    callback(new Error('密码至少6位'))
  } else {
    callback()
  }
}

const validateConfirm = (rule, value, callback) => {
  if (value !== form.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 预览图片
const previewImage = ref('');

// 处理头像选择变化
const handleAvatarChange = async (file) => {
  // 验证文件类型
  const isImage = file.raw.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('请上传图片文件!');
    return false;
  }

  // 验证文件大小
  const isLt2M = file.raw.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }

  const response = await PostFileUserImg(file.raw);
  if(response.data.code !== 200){
    ElMessage.error(response.data.message);
    return;
  }
  form.avatarUrl = response.data.data;

  // 创建预览图
  const reader = new FileReader();
  reader.onload = (e) => {
    previewImage.value = e.target.result;
  };
  reader.readAsDataURL(file.raw);

  return false; // 阻止自动上传
};

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 2, max: 16, message: '长度在2到16个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  newPassword: [
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirm, trigger: 'blur' }
  ]
}

// 头像上传处理
const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
  }
  return isImage && isLt2M
}
// 表单提交
const formRef = ref()
const submitting = ref(false)

const submitForm = async () => {
  submitting.value = true
  const res = await updateRePassword(form)
  if(res.code === 200){
    ElMessage.success('设置保存成功')
    if(form.newPassword != null && form.newPassword !== ''){
      localStorage.removeItem("token")
      userInformPink.clearAll()
      router.push('/admin/login')
    }
  }
  submitting.value = false
}

const resetForm = () => {
  formRef.value.resetFields()
}

onMounted(() => {
  getFormData()
})
</script>

<style scoped>
.settings-title {
  margin-bottom: 30px;
  color: #303133;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
  margin: 0 auto 20px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-tip {
  text-align: center;
  color: #909399;
  font-size: 12px;
}

.form-section {
  margin-bottom: 30px;
}

.section-title {
  color: #606266;
  margin: 0 0 20px 20px;
  font-size: 16px;
}
</style>
